import React, { Component } from 'react';

import moment from 'moment';

import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Input,
  Modal,
  Radio,
  Button,
  message,
  Divider,
  DatePicker,
} from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';

const { RangePicker } = DatePicker;

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1430304_y2xsdrlvrh.js',
});

interface SaveAndUpdateProps extends FormComponentProps {
  id: number;
  detail: any;
  From: string;
  visible: boolean;
  fetchAction: (typeName: string, payload?: any) => void;
  showModal: (status: boolean) => void;
}

interface SaveAndUpdateState {
  packageLadderList: {
    id: number;
    discount_id: number;
    discount_start: string;
    discount_end: string;
    discount: string;
    disabled: boolean;
  }[];
  per_packageLadderList: string;
  rangePickerMode: any;
  rangePickerValue: any;
  startTimeState: string;
  endTimeState: string;
  deleterIdList: any;
  open: boolean;
}

class SaveAndUpdateElem extends Component<SaveAndUpdateProps, SaveAndUpdateState> {
  state: SaveAndUpdateState = {
    packageLadderList: [
      {
        id: 0,
        discount_id: 0,
        discount_start: '',
        discount_end: '',
        discount: '',
        disabled: false,
      },
    ],
    per_packageLadderList: '',
    rangePickerMode: ['month', 'month'],
    rangePickerValue: [],
    startTimeState: '',
    endTimeState: '',
    deleterIdList: [],
    open: false,
  };

  static getDerivedStateFromProps(nextProps: SaveAndUpdateProps, perState: SaveAndUpdateState) {
    const { detail } = nextProps;
    const { per_packageLadderList } = perState;
    if (detail && detail.discount && detail.discount !== per_packageLadderList) {
      const new_deviceNoList = JSON.parse(detail.discount)
        .reverse()
        .map((item: any, index: number) => {
          item = {
            id: index,
            discount_id: item.id,
            discount_start: item.startCount,
            discount_end: item.endCount,
            discount: item.discount,
            disabled: true,
          };
          return item;
        });
      return {
        packageLadderList:
          new_deviceNoList.length > 0
            ? new_deviceNoList
            : [
              {
                id: 0,
                discount_id: 0,
                discount_start: '',
                discount_end: '',
                discount: '',
                disabled: false,
              },
            ],
        per_packageLadderList: detail.discount,
        startTimeState: detail.startTime,
        endTimeState: detail.endTime,
      };
    }
    return null;
  }

  componentWillUnmount() {
    const { fetchAction } = this.props;
    fetchAction('clear');
  }

  handleSubmit = () => {
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const discountStartList = values.discountList
        ? values.discountList.reduce((a: any, b: any) => a + parseInt(b.discount_start, 10), 0)
        : '';
      const discountEndList = values.discountList
        ? values.discountList
          .map((item: any) => ({
            discount_end: item.discount_end ? item.discount_end : 0,
          }))
          .reduce((a: any, b: any) => a + parseInt(b.discount_end, 10), 0)
        : '';

      const count = discountStartList
            - discountEndList
            - parseInt(values.discountList[0].discount_start, 10)
          === values.discountList.length - 1;
      if (!count) {
        message.error('区间设置不衔接');
        return;
      }

      const rangeValue = values.startEndTime;
      const list = values.discountList
        ? values.discountList.map(
          (item: any) => `${item.discount_start}-${item.discount_end}-${item.discount}`,
        )
        : [];

      const { id: vipId } = this.props;
      const params = {
        ...values,
        vipId,
        startDate: rangeValue ? rangeValue[0].format('YYYY-MM-01 HH:mm:ss') : '',
        endDate: rangeValue ? rangeValue[1].format('YYYY-MM-01 HH:mm:ss') : '',
        discountStr: list.join(','),
      };
      delete params.startEndTime;
      delete params.discountList;

      const { detail } = this.props;
      if (detail && detail.id) {
        params.id = detail.id;
        const { deleterIdList } = this.state;
        const deleterList = deleterIdList.map((item: any) => `${item}---`);
        const DetailList = values.discountList
          ? values.discountList.map(
            (item: any) => `${item.discount_id}-${item.discount_start}-${item.discount_end}-${item.discount}`,
          )
          : [];
        params.discountStr = DetailList.concat(deleterList).join(',');
        delete params.vipId;
      }

      const AllParams = {
        searchValue: {
          vipId,
          pageIndex: 1,
          pageSize: 10,
        },
        query: { ...params },
      };

      const { fetchAction } = this.props;
      fetchAction('saveAndUpdate', AllParams);
      fetchAction('clear');

      this.setState({
        deleterIdList: [],
        packageLadderList: [
          {
            id: 0,
            discount_id: 0,
            discount_start: '',
            discount_end: '',
            discount: '',
            disabled: false,
          },
        ],
        per_packageLadderList: '',
        rangePickerValue: [],
      });


      const { showModal } = this.props;
      showModal(false);
    });
  };

  handleCancel = () => {
    // 取消按钮
    const { showModal } = this.props;
    showModal(false);

    this.setState({
      packageLadderList: [
        {
          id: 0,
          discount_id: 0,
          discount_start: '',
          discount_end: '',
          discount: '',
          disabled: false,
        },
      ],
      per_packageLadderList: '',
      deleterIdList: [],
      rangePickerValue: [],
    });

    const { fetchAction } = this.props;
    fetchAction('clear');
  };

  handleChangeDelModal = (delVisible: boolean, values?: any) => {
    // 编辑删除
    const { packageLadderList, deleterIdList } = this.state;

    const Del_deviceNoList = [...packageLadderList];
    const deleterId = Del_deviceNoList[Del_deviceNoList.length - 1].discount_id;
    if (deleterId > 0) deleterIdList.push(deleterId);

    Del_deviceNoList.splice(Del_deviceNoList.length - 1, 1);
    Del_deviceNoList.map((item: any, key: number) => {
      item.id = key;
      return item;
    });

    this.setState({ packageLadderList: Del_deviceNoList }, () => {
      const { form: { resetFields } } = this.props;
      resetFields([`discountList[${packageLadderList.length - 2}].discount_end`]);
    });
  };

  handleDelNo = (index: number) => {
    // 新增删除输入框
    const { packageLadderList } = this.state;
    const Del_deviceNoList = [...packageLadderList];
    if (Del_deviceNoList.length === 1) {
      return;
    }

    Del_deviceNoList.splice(index, 1);
    Del_deviceNoList.map((item: any, key: number) => {
      item.id = key;
      return item;
    });

    this.setState({ packageLadderList: Del_deviceNoList }, () => {
      const { form: { resetFields } } = this.props;
      resetFields([`discountList[${packageLadderList.length - 2}].discount_end`]);
    });
  };

  handleSaveNo = () => {
    // 继续新增输入框
    const { packageLadderList } = this.state;
    this.setState({
      packageLadderList: [
        ...packageLadderList,
        {
          id:
            packageLadderList.length > 0
              ? packageLadderList[packageLadderList.length - 1].id + 1
              : 0,
          discount_id: 0,
          discount_start: '',
          discount_end: '',
          discount: '',
          disabled: false,
        },
      ],
    });
  };

  handleOpenChange = (open: any) => this.setState({ open });

  handleChange = (rangePickerValue: any) => this.setState({ rangePickerValue });

  handlePanelChange = (value: any, mode: any) => {
    this.setState({
      rangePickerValue: value,
      rangePickerMode: [
        mode[0] === 'date' ? 'month' : mode[0],
        mode[1] === 'date' ? 'month' : mode[1],
      ],
      startTimeState: value[0],
      endTimeState: value[1],
    });

    const { form: { setFields } } = this.props;
    setFields({
      startEndTime: [moment(value[0], 'YYYY-MM'), moment(value[1], 'YYYY-MM')],
    });
  };

  handleClose = () => this.setState({ open: false });

  renderdeviceNoList = () => {
    const NoList: any = [];
    const { packageLadderList } = this.state;
    const {
      form: { getFieldDecorator },
      From,
    } = this.props;

    packageLadderList.map((item: any, index: number) => {
      NoList.push(
        <Col md={24} sm={24} key={item.id} style={{ marginBottom: 20 }}>
          <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'left' }}>
            {From !== 'detail' && (
              <div style={{ marginRight: 8, width: 56 }}>
                {index === 0 && From !== 'detail' && (
                  <div className="operLink" onClick={this.handleSaveNo}>
                    <MyIcon type="iconjiahao" style={{ margin: '4px 4px 0 0' }} />
                    增加
                  </div>
                )}
                {index === 0 && item.disabled && From !== 'detail' && (
                  <div
                    className="operLink"
                    style={{ marginTop: 24, color: '#ff4d4f' }}
                    onClick={() => this.handleChangeDelModal(true, item)}
                  >
                    <MyIcon type="iconjianhao" style={{ margin: '4px 4px 0 0' }} />
                    删除
                  </div>
                )}
                {index === 0
                  && !item.disabled
                  && packageLadderList[0].discount_id === 0
                  && packageLadderList.length >= 2
                  && From !== 'detail' && (
                    <div
                      className="operLink"
                      style={{ marginTop: 24, color: '#ff4d4f' }}
                      onClick={() => this.handleDelNo(packageLadderList.length - 1)}
                    >
                      <MyIcon type="iconjianhao" style={{ margin: '4px 4px 0 0' }} />
                      删除
                    </div>
                )}
              </div>
            )}
            <div
              className="dottedBox"
              style={{
                display: 'flex',
                flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'flex-end',
                backgroundColor: '#FCFCFC',
                flex: 1,
              }}
            >
              <div style={{ width: '90%' }}>
                <Form.Item label="区间设置" colon={false} />
                <div style={{ display: 'flex', justifyContent: 'space-between', flex: 1 }}>
                  <Form.Item>
                    {getFieldDecorator(`discountList[${index}].discount_id`, {
                      initialValue: item.discount_id === 0 ? '' : item.discount_id,
                    })(
                      <Input
                        allowClear
                        hidden
                        disabled={From === 'detail'}
                        style={{ width: '99%' }}
                      />,
                    )}
                  </Form.Item>
                  <Form.Item>
                    {getFieldDecorator(`discountList[${index}].discount_start`, {
                      initialValue: item.discount_start,
                      rules: [
                        {
                          required: true,
                          message: '请输入区间设置',
                        },
                        {
                          pattern: /^[0-9]+$/,
                          message: '必须为整数',
                        },
                      ],
                    })(<Input allowClear disabled={From === 'detail'} style={{ width: '99%' }} />)}
                  </Form.Item>
                  <Form.Item className="marginL16">
                    {getFieldDecorator(`discountList[${index}].discount_end`, {
                      initialValue: index === packageLadderList.length - 1 ? '' : item.discount_end,
                      rules: [
                        {
                          required: index !== packageLadderList.length - 1,
                          message: '请输入区间设置',
                        },
                        {
                          pattern: /^[0-9]+$/,
                          message: '必须为整数',
                        },
                      ],
                    })(
                      <Input
                        allowClear
                        disabled={From === 'detail' || index === packageLadderList.length - 1}
                        style={{ width: '99%' }}
                      />,
                    )}
                  </Form.Item>
                </div>
              </div>
              <Divider type="vertical" style={{ height: '90%', margin: '0 20px' }} />
              <div style={{ width: '90%' }}>
                <Form.Item label="折扣设置（值范围：0-1）" colon={false} />
                <div style={{ display: 'flex', justifyContent: 'space-between', flex: 1 }}>
                  <Form.Item>
                    {getFieldDecorator(`discountList[${index}].discount`, {
                      // eslint-disable-next-line no-nested-ternary
                      initialValue: item.discount
                        ? (item.discount / 100).toFixed(2)
                        : From === 'detail' && packageLadderList[0].discount_id !== 0
                          ? '0.00'
                          : '',
                      rules: [
                        {
                          required: true,
                          message: '请输入折扣设置（值范围：0-1）',
                        },
                        {
                          pattern: /^0\.[0-9]{1,2}$|^0{1}$|^1{1}$|^1\.[0]{1,2}$/,
                          message: '必须为0-1之间,最多保留两位小数',
                        },
                      ],
                    })(<Input allowClear disabled={From === 'detail'} />)}
                  </Form.Item>
                </div>
              </div>
            </div>
          </div>
        </Col>,
      );
      return null;
    });

    return NoList;
  };

  render() {
    const {
      rangePickerMode,
      rangePickerValue,
      startTimeState,
      endTimeState,
      packageLadderList,
      open,
    } = this.state;

    const {
      form: { getFieldDecorator },
      detail,
      From,
      visible,
    } = this.props;

    return (
      <Modal
        title="配置优惠信息"
        width={680}
        visible={visible}
        destroyOnClose
        onCancel={this.handleCancel}
        footer={
          From === 'detail'
            ? [
              <Button key="back" type="primary" onClick={this.handleCancel}>
                关闭
              </Button>,
            ]
            : [
              <Button key="back" onClick={this.handleCancel}>
                取消
              </Button>,
              <Button key="submit" type="primary" onClick={this.handleSubmit}>
                确定
              </Button>,
            ]
        }
      >
        <Form hideRequiredMark className="tableListForm">
          <Row>
            <Col md={8} sm={24}>
              <Form.Item label="结算周期：" colon={false}>
                {getFieldDecorator('settleCycle', {
                  initialValue: 101,
                  rules: [{ required: true, message: '请选择结算周期' }],
                })(
                  <Radio.Group>
                    <Radio value={102} disabled>
                      周
                    </Radio>
                    <Radio value={101}>月</Radio>
                  </Radio.Group>,
                )}
              </Form.Item>
            </Col>
            <Col md={14} sm={24}>
              <Form.Item label="折扣方案：" colon={false}>
                {getFieldDecorator('settleType', {
                  initialValue: 103,
                  rules: [{ required: true, message: '请选择结算周期' }],
                })(
                  <Radio.Group>
                    <Radio value={103}>区间内折扣</Radio>
                    <Radio value={104} disabled>
                      总量折扣
                    </Radio>
                  </Radio.Group>,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={12}>
            <Col md={14} sm={24}>
              <Form.Item label="有 效  期：">
                {getFieldDecorator('startEndTime', {
                  initialValue:
                    detail && detail.startTime && detail.endTime
                      ? [moment(startTimeState, 'YYYY-MM'), moment(endTimeState, 'YYYY-MM')]
                      : rangePickerValue,
                  rules: [{ required: true, message: '请选择结算周期' }],
                })(
                  <RangePicker
                    allowClear={false}
                    mode={rangePickerMode}
                    format="YYYY-MM"
                    open={open}
                    onOpenChange={this.handleOpenChange}
                    onChange={this.handleChange}
                    onPanelChange={this.handlePanelChange}
                    renderExtraFooter={() => (
                      <Button type="primary" style={{ height: 28 }} onClick={this.handleClose}>
                        关闭
                      </Button>
                    )}
                    style={{ float: 'right' }}
                    disabled={From === 'detail'}
                  />,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Form.Item label="揽件阶梯设置:" colon={false} style={{ marginBottom: 20 }} />
            <Row gutter={12}>
              <div>
                {packageLadderList.length === 0 && (
                  <div style={{ paddingLeft: 34 }}>
                    <div className="operLink" onClick={this.handleSaveNo}>
                      <MyIcon type="iconjiahao" style={{ margin: '4px 4px 0 0' }} />
                      增加
                    </div>
                  </div>
                )}
                {this.renderdeviceNoList()}
              </div>
            </Row>
          </Row>
        </Form>
      </Modal>
    );
  }
}

export default Form.create<SaveAndUpdateProps>()(SaveAndUpdateElem);
